/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react/jsx-key */
import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import { Card, Switch, Button, Modal, message, Popconfirm } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { area, user, classify } from '@/services/basic';
import { company } from '@/services/business';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment';
import { useMemo } from 'react';
import Tax from './tax';
import CompanyName from '@/components/CompanyName';

// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

function Taxnotice(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState({
      company_id: {
        value: null,
        type: 'select',
        title: '代账公司',
        name: ['company_id'],
        required: true,
        options: {
          database: company,
          params: {
            is_all: 1,
          },
        },
        col: { span: 24 },
      },
      tax: {
        value: null,
        type: 'inputnumber',
        title: '税费',
        name: ['tax'],
        required: true,
      },
      tax_time: {
        value: null,
        type: 'datepicker',
        title: '申报月份',
        name: ['tax_time'],
        format: 'YYYY-MM',
        required: true,
        disabledDate: (current) => {
          return current && current > moment().endOf('day');
        },
        picker: 'month',
      },
    }),
    [key, setkey] = useState('1'),
    [iftype, ciftype] = useState({});

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = useMemo(() => {
    if (key == '1') {
      return [
        {
          title: '公司名称',
          width: 260,
          dataIndex: 'company_name',
          key: 'company_name',
          render: (_, row) => (
            <CompanyName
              row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
              reload={reload}
            />
          ),
        },
        {
          title: '公司类型',
          dataIndex: 'classify_name',
          key: 'classify_id',
          valueType: 'select',
          options: {
            database: classify,
            params: { is_all: 1 },
          },
        },
        {
          title: '客户名称',
          dataIndex: 'customer_name',
          key: 'customer_name',
        },
        {
          title: '客户编号',
          dataIndex: 'code',
          key: 'code',
        },
        {
          title: '税费',
          dataIndex: 'tax_info',
          key: 'tax_info',
          search: false,
          render: (_, row) => {
            return <b>{row?.tax_info?.tax ?? <span style={{ color: '#DDD' }}>暂未申报</span>}</b>;
          },
        },
        {
          title: '操作',
          valueType: 'option',
          width: 160,
          render: (text, row, _, action) => {
            return (
              <Button
                type="link"
                disabled={row.account_user_id != props.user.currentUser.id}
                onClick={() => {
                  if (row?.tax_info?.tax) {
                    message.warn(row.name + '本月已申报！');
                    return;
                  }
                  cvs(true);
                  cf((fields) => {
                    for (let i in fields) {
                      fields[i].value = null;
                      if (i == 'company_id') {
                        fields[i].value = row.id;
                        fields[i].disabled = true;
                      }
                      if (i == 'tax_time') {
                        fields[i].value = moment();
                        fields[i].disabled = true;
                      }
                    }
                    return { ...fields };
                  });
                  ciftype({
                    val: 'add',
                    title: '税务申报',
                  });
                }}
              >
                税务申报
              </Button>
            );
          },
        },
      ];
    } else {
      return [
        {
          title: '公司名称',
          width: 260,
          dataIndex: 'company_name',
          key: 'company_name',
          render: (_, row) => (
            <CompanyName
              row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
              reload={reload}
            />
          ),
        },
        {
          title: '公司类型',
          dataIndex: 'classify_name',
          key: 'classify_id',
          valueType: 'select',
          options: {
            database: classify,
            params: { is_all: 1 },
          },
        },
        {
          title: '客户名称',
          dataIndex: 'customer_name',
          key: 'customer_name',
          search: false,
        },
        {
          title: '申报月份',
          dataIndex: 'tax_time',
          key: 'tax_time',
          search: false,
        },
        {
          title: '税费',
          dataIndex: 'tax',
          key: 'tax',
          search: false,
        },
      ];
    }
  }, [key]);

  let extrarender = [
    <div
      className="action"
      title="新增"
      onClick={() => {
        cvs(true);
        cf((fields) => {
          for (let i in fields) {
            fields[i].value = null;
            fields[i].disabled = false;
          }
          return { ...fields };
        });
        ciftype({
          val: 'add',
          title: '税务申报',
        });
      }}
    >
      <PlusOutlined />
    </div>,
  ];

  let saveData = (values) => {
    let { dispatch } = props;
    if (iftype.val == 'add') {
      dispatch({
        type: 'customer/addcompany_tax',
        payload: values,
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };
  const [selectedRowKeys, setselectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);

  return (
    <div className="pgcontainer">
      <AutoTable
        tabList={[
          {
            key: '1',
            tab: '本月报送',
          },
          {
            key: '2',
            tab: '全部报送',
          },
        ]}
        onTabChange={(val) => {
          setkey(val);
        }}
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        tabBarExtraContent={
          <a
            disabled={selectedRowKeys.length === 0}
            style={{ marginLeft: 12 }}
            onClick={() => {
              if (selectedRowKeys.length === 0) {
                return;
              }
              cvs(true);
              cf((fields) => {
                for (let i in fields) {
                  fields[i].value = null;
                  fields[i].disabled = false;
                }
                return { ...fields };
              });
              ciftype({
                val: 'report',
                title: '税务申报',
              });
            }}
          >
            税务申报
          </a>
        }
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path={
          key == '1'
            ? '/wbn-api/company_tax/current_company_tax'
            : '/wbn-api/company_tax/tax_record'
        }
        extraparams={{ account_user_id: props.user.currentUser.id }}
        rowSelection={{
          selectedRowKeys: selectedRowKeys,
          preserveSelectedRowKeys: true,
          onChange: (selectedRowKeys, selectedRows) => {
            setselectedRowKeys(selectedRowKeys);
            setSelectedRows(selectedRows);
          },
          getCheckboxProps: (row) => ({
            disabled: row.account_user_id != props.user.currentUser.id, // Column configuration not to be checked
          }),
        }}
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={
          iftype?.val === 'report' ? (
            <Button
              type="primary"
              onClick={async () => {
                let { dispatch } = props;
                if (selectedRows.some((it) => !it?.tax)) {
                  message.warn('存在未填写的税费!');
                  return;
                }
                const doarr = [],
                  errarr = [];

                async function asyncMap() {
                  const promises = selectedRows.map(async (it) => {
                    let res = await dispatch({
                      type: 'customer/addcompany_tax',
                      payload: {
                        company_id: it?.id,
                        tax: it?.tax,
                        tax_time: moment().format('YYYY-MM'),
                      },
                    });
                    if (res.code == 0) {
                      doarr.push(it?.name);
                    } else {
                      errarr.push(it?.name);
                    }
                  });
                  return Promise.all(promises);
                }

                await asyncMap();
                message.destroy();
                if (doarr.length === selectedRows.length) {
                  message.success('报税成功');
                  setSelectedRows([]);
                  setselectedRowKeys([]);
                  reload();
                  cvs(false);
                } else {
                  message.error('报税失败，失败的公司有：' + errarr?.join(','));
                }
              }}
            >
              报税
            </Button>
          ) : (
            false
          )
        }
        destroyOnClose={true}
        width={iftype.val === 'report' ? 1200 : 600}
      >
        {iftype.val === 'report' ? (
          <div>
            <Tax
              dataSource={selectedRows ?? []}
              value={selectedRows ?? []}
              onValuesChange={(val) => {
                setSelectedRows([...val]);
              }}
              editable={{
                editableKeys: selectedRows?.map?.((it) => it.id) ?? [],
              }}
            />
          </div>
        ) : (
          <InitForm
            fields={fields}
            submitData={(values) => {
              saveData(values);
            }}
            onChange={(changedValues, allValues) => {
              //联动操作
            }}
            submitting={props.loading.effects['customer/company_tax'] || !vs}
          />
        )}
      </Modal>
    </div>
  );
}

export default connect(({ customer, user, loading }) => ({
  customer,
  user,
  loading,
}))(Taxnotice);
